package mime.aop;

import javassist.*;
import org.junit.Test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 广州奥凯信息咨询有限公司
 * <p>
 * 本源代码由《项目一组》及其作者共同所有，未经版权持有者的事先书面授权，
 * 不得使用、复制、修改、合并、发布、分发和/或销售本源代码的副本。
 *
 * @copyright Copyright (广州奥凯信息咨询有限公司) 2019-2022. all rights reserved.
 */

public class DemoOfAop {
    @Test
    public void aop() throws NotFoundException, CannotCompileException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        ClassPool classPool = ClassPool.getDefault();
        CtClass person = classPool.get("mime.Person");
        CtMethod setName = person.getDeclaredMethod("setName");
        setName.insertBefore("System.out.println(\"_\");");

        Class<?> aClass = person.toClass();
        Method method = aClass.getMethod("setName", String.class);

        Object instance = aClass.getDeclaredConstructor().newInstance();
        method.invoke(instance, "maikec");

        Method getName = aClass.getMethod("getName");
        Object invoke = getName.invoke(instance);
        System.out.println(invoke);
    }
}
